<template>
  <div class="home">
    <div class="title-container">
      <div class="search-content">
        <el-form :model="searchModel" :inline="true">
          <el-form-item>
            <el-input
              v-model="searchModel.userName"
              :disabled="detailsDisabled"
              placeholder="请输入设备名称"
              prefix-icon="el-icon-search"
            />
          </el-form-item>
        </el-form>
        <div class="search-btn">
          <el-button
            type="primary"
            icon="el-icon-search"
            @click="searchClick"
            size="medium"
          >搜索
          </el-button>
        </div>
      </div>
    </div>

    <el-card>
      <div class="addAccount">
        <el-button
          type="success"
          icon="el-icon-refresh"
          size="medium"
          @click="refresh"
        >刷新
        </el-button>
      </div>
      <el-table
        v-loading="loading"
        :data="tableData"
        row-key="id"
        border
        style="width: 100%;"
        class="elTable"
      >
        <el-table-column type="index" label="序号" width="50" align="center"/>
        <el-table-column prop="deviceCode" label="设备编码" align="center"/>
        <el-table-column prop="deviceName" label="设备名称" align="center"/>
        <el-table-column prop="sourceName" label="数据源名称" align="center"/>
        <el-table-column prop="deviceDes" label="设备描述" align="center"/>
        <el-table-column label="是否网关设备" align="center">
          <template slot-scope="scope">
            {{ scope.row.isNet=='yes'?'是':'否' }}
          </template>
        </el-table-column>
        <el-table-column prop="modelName" label="模型名称" align="center"/>
        <el-table-column prop="modelType" label="模型类型" align="center"/>
        <el-table-column prop="deviceTypeName" label="设备类型名称" align="center"/>
        <el-table-column prop="tagName" label="自定义标签名称" align="center"/>
        <!--        <el-table-column prop="createByName" label="创建人" align="center"/>-->
        <!--        <el-table-column label="创建时间" align="center" prop="createTime">-->
        <!--          <template slot-scope="scope">-->
        <!--            {{ scope.row.createTime }}-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <!--        <el-table-column prop="updateByName" label="更新人" align="center"/>-->
        <!--        <el-table-column label="更新时间" align="center" prop="createTime">-->
        <!--          <template slot-scope="scope">-->
        <!--            {{ scope.row.updateTime }}-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <el-table-column label="操作" width="250" align="center">
          <template #default="{ row }">
            <perButton label="设备配置" type="primary" size="mini" perms="PT_USER_EDIT"
                       @click="handlerDeviceConfig(row)"></perButton>
            <perButton label="通讯参数" type="primary" size="mini" perms="PT_USER_EDIT"
                       @click="handlerCommunicationParam(row)"></perButton>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        class="pagination"
        :total="count"
        :page.sync="pageIndex"
        :limit.sync="pageSize"
        @pagination="getAccountData"
      />
    </el-card>

    <!-- 设备配置 -->
    <yc-dialog ref="ycDialog" :dialogTitle="dialogTitle" :show-center="false" dialog-width="40%">
      <template #content>
        <div class="dialog-content">
          <el-form
            ref="newAccountFormRef"
            :rules="newAccountModelRules"
            :model="newAccountModel"
            :disabled="detailsDisabled"
            label-width="110px"
          >
            <el-form-item label="设备类型标签" prop="deviceTypeCode">
              <el-select v-model="newAccountModel.deviceTypeCode" placeholder="请选择" style="width: 100%;">
                <el-option
                  v-for="item in deviceTypeList"
                  :key="item.deviceTypeCode"
                  :label="item.deviceTypeName"
                  :value="item.deviceTypeCode"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="自定义标签" prop="tagCode">
              <el-cascader
                v-model="newAccountModel.tagCode"
                style="width: 100%;"
                ref="cascaderHandleRef"
                @change="handleSelectChange"
                :options="tagList"
                :props="tagProps"
                clearable></el-cascader>
            </el-form-item>
          </el-form>
        </div>
      </template>
      <template #footer>
        <el-button type="primary" :loading="addOrUpdateLoading" @click="dialogSave">确定</el-button>
        <el-button @click="$refs.ycDialog.dialogVisible = false">取消</el-button>
      </template>
    </yc-dialog>

    <!-- 通讯参数 -->
    <yc-dialog ref="paramDialog" :dialogTitle="dialogTitle" :show-center="false">
      <template #content>
        <div class="dialog-content" v-loading="loading2" element-loading-text="拼命加载中"
             element-loading-spinner="el-icon-loading">
          <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选
          </el-checkbox>
          <div style="margin: 15px 0;"></div>
          <el-checkbox-group v-model="checkedParams" @change="handleCheckedCitiesChange">
            <el-checkbox v-for="item in paramOption" :label="item" :key="item.parameterCode">
              {{item.parameterName}}
            </el-checkbox>
          </el-checkbox-group>
        </div>
      </template>
      <template #footer>
        <el-button type="primary" :loading="addOrUpdateLoading" @click="dialogSaveParam">保存配置并下发IOT</el-button>
        <el-button @click="$refs.paramDialog.dialogVisible = false">取消</el-button>
      </template>
    </yc-dialog>

    <!-- 封装操作后弹框 -->
    <global-message
      v-if="isGlobalMessageShow"
      @receive="receive"
      :message="message"
    />
  </div>
</template>

<script>
  import ycDialog from "@/components/pageDialog"
  import perButton from "@/components/permissionButton"

  import {
    queryPage,
    queryParameterList,
    saveParameterList,
    queryDeviceTagList,
    saveDeviceTag
  } from "@/api/dataInsertConfig/internetOfThingsDevice"

  export default {
    components: {
      ycDialog,
      perButton
    },
    data() {
      return {
        isGlobalMessageShow: false,
        message: "",

        projectCode: "",
        tableData: [],
        dataItemObj: {},
        count: 0,
        pageIndex: 1,
        pageSize: 10,
        loading: false,

        searchModel: {
          userName: "",
          status: null //正常/停用状态（全部）
        },

        newAccountModel: {
          deviceTypeCode: "",
          tagCode: []
        },
        newAccountModelRules: {
          deviceTypeCode: [{required: true, message: '请选择设备类型标签', trigger: 'change'}],
          tagCode: [{required: true, message: '请选择自定义标签', trigger: 'change'}],
        },

        deviceTypeList: [],
        tagList: [],
        tagProps: {
          label: 'tagName',
          value: 'tagCode',
          children: 'childList',
          checkStrictly: true,
          expandTrigger: 'click'
        },

        dialogTitle: "",
        centerTitle: "",

        checkAll: false,
        checkedParams: [],
        paramOption: [],
        isIndeterminate: false,
        loading2: true,

        detailsDisabled: false,
        addOrUpdateLoading: false
      }
    },
    created() {
      this.projectCode = sessionStorage.getItem('projectCode')
      this.getAccountData()
    },
    methods: {
      /**
       * 获取表格方法
       */
      async getAccountData(tableInfo) {
        this.loading = true
        if (tableInfo) {
          const {userName, status} = tableInfo
          const {object} = await queryPage({
            projectCode: this.projectCode,
            deviceCom: '0',
            pageIndex: this.pageIndex,
            pageSize: this.pageSize,
            userName,
            status
          })
          this.tableData = object.data
          this.count = object.count
          this.loading = false
        } else {
          const {object} = await queryPage({
            projectCode: this.projectCode,
            deviceCom: '0',
            pageIndex: this.pageIndex,
            pageSize: this.pageSize
          })
          this.tableData = object.data
          this.count = object.count
          this.loading = false
        }
      },
      pagination(pageItem) {
        this.getAccountData(pageItem.page, pageItem.limit)
      },
      // 搜索按钮
      async searchClick() {
        this.getAccountData(this.searchModel)
      },

      // 设备配置
      handlerDeviceConfig(row) {
        this.dialogTitle = "设备配置"

        this.dataItemObj = row
        this.newAccountModel.deviceTypeCode = row.deviceTypeCode
        this.newAccountModel.tagCode = row.tagAllCode ? row.tagAllCode.split('-') : []

        this.queryDeviceTagList()

        this.addOrUpdateLoading = false
        this.$refs.ycDialog.dialogVisible = true
      },

      queryDeviceTagList() {
        queryDeviceTagList({
          projectCode: this.projectCode,
          deviceCode: this.dataItemObj.deviceCode,
        }).then(res => {
          const tempArr = res.object || {}

          this.deviceTypeList = tempArr.deviceTypeList
          this.tagList = tempArr.ownerList
        })
      },
      handleSelectChange(node) {
        // if (!this.$refs.cascaderHandleRef.getCheckedNodes()[0]?.hasChildren) {
          this.$refs.cascaderHandleRef.dropDownVisible = false;
        // }
      },
      dialogSave() {
        this.$refs.newAccountFormRef.validate(async (v) => {
          if (v) {
            const {deviceTypeCode, tagCode} = this.newAccountModel
            saveDeviceTag({
              projectCode: this.projectCode,
              deviceCode: this.dataItemObj.deviceCode,
              deviceTypeCode,
              tagCode: tagCode[tagCode.length - 1]
            }).then(res => {
              if (res.status == 200) {
                this.getAccountData()
                this.$refs.ycDialog.dialogVisible = false
                this.$message.success(message)
              }
            })
          }
        })
      },

      /**
       * 通讯参数
       */
      async handlerCommunicationParam(row) {
        this.dialogTitle = "通讯参数"

        this.checkedParams = []
        this.dataItemObj = JSON.parse(JSON.stringify(row))

        this.addOrUpdateLoading = false
        this.detailsDisabled = false
        this.$refs.paramDialog.dialogVisible = true

        await this.queryParameterList()

        this.handleCheckedCitiesChange(this.checkedParams)
      },
      handleCheckAllChange(val) {
        this.checkedParams = val ? this.paramOption : [];
        this.isIndeterminate = false;
      },
      handleCheckedCitiesChange(value) {
        let checkedCount = value.length;
        this.checkAll = checkedCount === this.paramOption.length;
        this.isIndeterminate = checkedCount > 0 && checkedCount < this.paramOption.length;
      },
      async queryParameterList() {
        this.loading2 = true
        await queryParameterList({
          deviceCode: this.dataItemObj.deviceCode
        }).then(res => {
          const arrTemp = res.object || []
          this.paramOption = arrTemp
          for (let i = 0; i < arrTemp.length; i++) {
            if (arrTemp[i].messages == 1) {
              this.checkedParams.push(arrTemp[i])
            }
          }
          this.loading2 = false
        })
      },
      async dialogSaveParam() {
        if (this.checkedParams.length == 0) {
          this.$message({
            message: '请选择通讯参数',
            type: 'warning'
          });

          return
        }
        this.addOrUpdateLoading = true
        let arr = this.checkedParams.map(item => {
          return {
            parameterName: item.parameterName,
            parameterCode: item.parameterCode,
          }
        })
        const {message, status} = await saveParameterList({
          deviceCode: this.dataItemObj.deviceCode,
          messages: JSON.stringify(arr)
        })
        if (status == 200) {
          this.getAccountData()
          this.$refs.paramDialog.dialogVisible = false
          this.$message.success(message)
        }
        this.addOrUpdateLoading = false
      },

      /**
       * 刷新
       */
      refresh() {
        this.searchModel = {
          userName: "",
          status: null
        }
        this.getAccountData()
      },

      /**
       * globalMessage的知道按钮的方法
       * */
      receive() {
        this.isGlobalMessageShow = false
      },
    }
  }
</script>

<style lang="scss" scoped>
  .status {
    display: inline-block;
    padding: 0 10px;
  }

  .title-container {
    display: flex;
    justify-content: flex-end;
    height: 60px;

    .search-content {
      margin-left: 20px;
      display: flex;
    }

    .addAccount {
      margin: 10px 20px;
    }
  }

  .pagination {
    display: flex;
    justify-content: flex-end;
  }


  .footer {
    height: 360px;
    display: flex;
    align-items: flex-end;
    // justify-content: st-end;
    padding: 5px 20px;
  }
</style>
